package com.example.utils;



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;

/**
 * k3API接口调用类
 * Created by tony on 2017/8/23.
 */
public class k3Api {
    public  String apiUrl = "http://192.168.123.246/K3API/";                      //API地址
//    public String authCode = "cc7c2a733c0a29ec26272a9711dd42418dd330713a6acdce";  //我的授权码
    //public String authCode = "94b6082fce6fb8e80dfbdc93b5e6c551e1dcf835335ea58f";  //测试帐套授权码
    //public String authCode ="71dcfd6f3cd7e764a4a91a31d80039adc69e867e9e1ed893";
    public  String authCode="785b9b26c2ba81886cc105f3d5d10ae2c0ab86d5def9bf5e"; //正式帐套授权码
    /**
     * 取得K3的Token
     */
    public String getToken(){
        String url=apiUrl+"Token/Create/?authorityCode="+authCode+"&language=CHS";
        return callUrl(url,"");
    }


    /**
     * 调用k3api接口
     */
    public String callK3Api(String callUrl,String token,String param){
        //String url=apiUrl+callUrl+"?token="+token;
        String url=apiUrl+callUrl+"?acct=4e19fe138d6509bc&language=chs&token="+token;
        return callUrl(url,param);
    }
    /**
     * 取得K3的Token
     */
    public String callUrl(String callUrl,String param){

        PrintWriter out = null;
        BufferedReader in = null;
        String UrlResult = "";
        try {
            URL realUrl = new URL(callUrl);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                UrlResult += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return UrlResult;
    }
}

